package com.itheima.huikebackend.common;

import com.itheima.huikebackend.enums.HttpStatusCodeEnum;

import java.io.Serializable;
import java.util.Map;
import java.util.Objects;

public class Result<T> implements Serializable {

    private static final long serialVersionUID = 42L;
    private final static String SUCCESS_TEXT = "ok";
    private final static Integer SUCCESS_CODE = HttpStatusCodeEnum.SUCCESS_CODE.code;
    private final static Integer ERROR_CODE = HttpStatusCodeEnum.ERROR_CODE.code;


    private Integer code;
    private T data;
    private String msg;

    private Result() {}

    private Result(Integer code, T data, String msg) {
        this.code = code;
        this.data = data;
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public static Result<?> success () {
        return new Result<>(SUCCESS_CODE, null, SUCCESS_TEXT);
    }

    public static <T> Result<T> success(T data) {
        return new Result<>(SUCCESS_CODE, data, SUCCESS_TEXT);
    }

    public static <T> Result<T> success(Integer code, T data) {
        return new Result<>(code, data, SUCCESS_TEXT);
    }

    public static <T> Result<T> error(String msg) {
        return new Result<>(ERROR_CODE, null, msg);
    }

    public static <T> Result<T> error(Integer code, String msg) {
        return new Result<>(code, null, msg);
    }

    public static Map<String,Object> successMap(Map<String, Object> map) {
        map.put("code", SUCCESS_CODE);
        map.put("msg", SUCCESS_TEXT);
        return map;
    }

    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", data=" + data +
                ", msg='" + msg + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o){
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Result<?> result = (Result<?>) o;
        return Objects.equals(code, result.code) && Objects.equals(data, result.data) && Objects.equals(msg, result.msg);
    }

    @Override
    public int hashCode() {
        return Objects.hash(code, data, msg);
    }
}
